/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'package:hadss_adaptive_layout/hadss_adaptive_layout.dart';
import 'package:hadss_uni_input/hadss_uni_input.dart';
import 'package:samples/utils/music_tools.dart';

import '../l10n/generated/app_localizations.dart';

class MusicListItemWidget extends StatefulWidget {
  final Map data;
  final Function itemClick;
  final Function menuClick;
  final Function itemDoubleClick;
  final WidthBreakpoint screenType;

  const MusicListItemWidget(
      {super.key,
      required this.data,
      required this.itemClick,
      required this.menuClick,
      required this.itemDoubleClick,
      this.screenType = WidthBreakpoint.xs});

  @override
  State<MusicListItemWidget> createState() => _MusicListItemWidgetState();
}

class _MusicListItemWidgetState extends State<MusicListItemWidget> {
  final panDirection = PanDirection.all.value;
  final GlobalKey _globalKey = GlobalKey();
  double titleFont = 16;

  @override
  Widget build(BuildContext context) {
    return UnifiedGestureDetector(
      onTap: () {
        widget.itemClick();
      },
      onDoubleTap: () {
        widget.itemDoubleClick();
      },
      child: Container(
        margin: const EdgeInsets.only(left: 15, right: 15),
        height: 68,
        decoration: const BoxDecoration(
            border:
                Border(bottom: BorderSide(color: Color(0x0d000000), width: 1))),
        child: Row(
          children: buildItems(),
        ),
      ),
    );
  }

  List<Widget> buildItems() {
    List<Widget> items = [];
    AppLocalizations il8n = AppLocalizations.of(context)!;
    items.add(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              UnifiedGestureDetector(
                onHover: onHover,
                child: Text(
                  widget.data["title"] ?? "",
                  style: TextStyle(
                      fontSize: titleFont,
                      fontWeight: FontWeight.w500,
                      color: Colors.black),
                ),
              ),
              const SizedBox(
                width: 5,
              ),
              Visibility(
                visible: widget.data["select"] == 1,
                child: Image.asset(
                  "lib/assets/images/heart_select.png",
                  width: 14,
                  height: 14,
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Image.asset(
                "lib/assets/images/list_tag_icon.png",
                width: 20,
                height: 12,
              ),
              Text(
                widget.data["subtitle"] ?? "",
                style: const TextStyle(fontSize: 12, color: Color(0xffFF1949)),
              ),
              Text(
                " - ${il8n.name}",
                style: const TextStyle(fontSize: 12, color: Color(0x99000000)),
              ),
            ],
          )
        ],
      ),
    );
    items.add(
      const Expanded(child: SizedBox()),
    );
    items.add(
      UnifiedGestureDetector(
        pointerOptions: const PointerOptions(),
        onContentMenu: onContentMenu,
        child: Container(
          padding: const EdgeInsets.only(left: 20, top: 10, bottom: 10),
          child: Image.asset(
            "lib/assets/images/more_icon.png",
            width: 15,
            height: 15,
            key: _globalKey,
          ),
        ),
      ),
    );
    return items;
  }

  void onContentMenu(GestureEvent event) {
    if (event.localPosition == null) {
      return;
    }
    showMenuView();
  }

  void showMenuView() {
    final RenderBox renderBox =
        _globalKey.currentContext!.findRenderObject() as RenderBox;
    final localToGlobal = renderBox.localToGlobal(Offset.zero);
    double width = 60;
    if (widget.screenType == WidthBreakpoint.xs ||
        widget.screenType == WidthBreakpoint.sm) {
      width = 0;
    }
    renderBox.localToGlobal(Offset.zero);
    Size size = renderBox.size;
    double left = localToGlobal.dx - 120 - width;
    double top = localToGlobal.dy + size.height;
    double right = MediaQuery.of(context).size.width - localToGlobal.dx;
    double bottom = 0;
    showMenu(
        context: context,
        position: RelativeRect.fromLTRB(
          left,
          top,
          right,
          bottom,
        ),
        shadowColor: const Color(0x4d000000),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
        ),
        items: MusicTools().buildMenuItemList(
            context: context,
            data: widget.data,
            menuClick: (value) {
              setState(() {
                widget.menuClick(value);
              });
            })).then((value) {});
  }

  void onHover(bool isHover, PointerEvent event) {
    if (mounted) {
      setState(() {
        titleFont = isHover ? 20 : 16;
      });
    }
  }
}
